package com.xzp.service;

import com.xzp.entity.Girl;
import com.xzp.entity.Result;
import com.xzp.enums.ResultEnum;
import com.xzp.exception.GirlException;
import com.xzp.repository.GirlRepository;
import com.xzp.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;

import javax.validation.Valid;
import java.util.List;


@Service
public class GirlService {

    @Autowired
    private GirlRepository girlRepository;


    //注意导入的包是org.springframework.transaction.annotation.Transactional
    @Transactional
    public void insertTwo(){
        Girl girlA = new Girl();
        girlA.setAge(20);
        girlA.setCupSize("B");
        girlA.setMoney(0.0);
        girlRepository.save(girlA);

        Girl girlB = new Girl();
        girlB.setAge(19);
        girlB.setCupSize("CC");
        girlB.setMoney(0.0);
        girlRepository.save(girlB);

    }


    public List<Girl> girlList(){
        return girlRepository.findAll();
    }

    public Result<Girl> girlAdd(Girl girl){  //使用对象接受参数 验证结果保存在对象

        return ResultUtil.success(girlRepository.save(girl));
    }

    public Result<Girl> girlFindOne(Integer id){
//        return girlRepository.findOne(id); 老版本写法
        Girl girl = girlRepository.findById(id).orElse(null);  //SpringBoot 2.0+ 新写法
        if (girl != null)
            return ResultUtil.success(girl);
        else {
            return ResultUtil.error(1,"查找无结果");
        }

    }

    //根据id删除
    public Result girlDelete(Integer id){
        if (girlRepository.existsById(id)){
            girlRepository.deleteById(id);
            return ResultUtil.success();
        }

        return ResultUtil.error(1,"删除失败");
    }

    /**
     * 更新
     * @param girl
     * @return
     */
    public Result<Girl> girlUpdate(Girl girl){

        return ResultUtil.success( girlRepository.save(girl));
    }


    public Result getAge(Integer id) throws Exception{
        Girl girl = girlRepository.findById(id).get();  //springboot2.0
        Integer age = girl.getAge();
        if (age < 10){
//            throw new Exception(ResultEnum.PRIMARY_SCHOOL);
//            throw new Exception("上小学");
            throw new GirlException(ResultEnum.PRIMARY_SCHOOL);
        }else if (age >10 && age < 16){
            throw new GirlException(ResultEnum.MIDDLE_SCHOOL);
        }

        return ResultUtil.success(girl.getAge());
    }
}
